package com.onekbase.demo.tcp;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpServerBioDemo {
    public static void main(String[] args) {
        try {
            int port = 8084;
            ServerSocket serverSocket = new ServerSocket(port);
            System.out.println("Server started on port "+port);
            while (true) {
                Socket clientSocket = serverSocket.accept();
                try(InputStream inputStream = clientSocket.getInputStream();
                    OutputStream outputStream = clientSocket.getOutputStream();){
                    byte[] buffer = new byte[1024];
                    int bytesRead = inputStream.read(buffer);
                    String clientData = new String(buffer, 0, bytesRead);
                    System.out.println("Received from client: " + clientData);
                    Thread.sleep(200);
                    String response = "Hello from the middle server";
                    outputStream.write(response.getBytes());
                }catch (Exception e) {
                    e.printStackTrace();
                }finally {
                    clientSocket.close();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}